package com.kaiyidiannao.activity.auction;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.kaiyi.diannao.net.AsyncHttpResponseParse;
import com.kaiyi.diannao.net.LoadDataHandler;
import com.kaiyi.diannao.net.RequestClient;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.AppUtils;
import com.kaiyidiannao.common.util.DateTimeUtils;
import com.kaiyidiannao.common.util.UploadImageUtils;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.imagescale.ImageGalleryActivity;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.Auction;
import com.kaiyidiannao.widget.LoadingDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.common.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class UploadAuctionActivity extends BaseActionBarActivity {

    private static final String TAG = "UploadAuctionActivity";

	private TextView mTxtPatUpload;
	
    private ImageView mImg0;
    private ImageView mImg1;
    private ImageView mImg2;
    private ImageView mImg3;
    private ImageView mImg4;
    private ImageView mImg5;
    private ImageView mImg6;
    private ImageView mImg7;
    
    private int mIndex = 0;
    
    private ImageView mImgPatBack;
    private EditText mEdtPriceMin;
    private EditText mEdtAddPrice;
    private TextView mTxtCategory;
    private EditText mEditName;
    private EditText mEdtContent;
    
    private TextView mStartTimeTextView;
    private TextView mEndTimeTextView;
    
    private int[] mCategoryIds = {66, 67, 68, 69, 70, 71};
    private int mSelectCategoryId;
    
    private String mPriceMin;
    private String mAddPrice;
    private String mStartTime;
    private String mEndTime;
    private String mTitle;
    private String mIntroduce;
    
//    private List<ImageView> imageViewList = new ArrayList<ImageView>();
    private static final String IMAGE_FILE_NAME = "faceImage";
    private String[] mImagePaths = new String[8];
    private String[] items = new String[] { "选择本地图片", "拍照" };

    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auction_upload);

    	mSelectCategoryId = mCategoryIds[0];
    	
        findView();
        initListener();
        initDialog();
        initImageListener();
        
        setupUI(findViewById(R.id.scrollview));
    }
    
 // 点击EditText以外的地方, 隐藏软键盘和功能选项
 	private void setupUI(View view) {
 	    //Set up touch listener for non-text box views to hide keyboard.
 	    if(!(view instanceof EditText)) {
 	    	
 	        view.setOnTouchListener(new View.OnTouchListener() {
 	        	
 	        	@Override
 	            public boolean onTouch(View v, MotionEvent event) {
 	                hideKeyboard();
 	                return false;
 	            }
 	        });
 	    }
 	    
 	    //If a layout container, iterate over children and seed recursion.
	    if (view instanceof ViewGroup) {
	        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
	            View innerView = ((ViewGroup) view).getChildAt(i);
	            setupUI(innerView);
	        }
	    }
 	}
 	
 	/**
	 * 隐藏输入法面板
	 */
	@SuppressWarnings("static-access")
	protected void hideKeyboard() {
		InputMethodManager imm = ((InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE));
		if (imm != null && getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
    
    private void initDialog() {
		mLoadingDialog = new LoadingDialog(this);
		mLoadingDialog.setCanceledOnTouchOutside(false);
		mLoadingDialog.setText("提交数据中...");
		mLoadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				mLoadingDialog.dismiss();
				//RequestClient.cancal(UploadAuctionActivity.this);
			}
		});
	}

    private void findView() {
    	mImgPatBack = (ImageView) findViewById(R.id.img_pat_back);
    	mTxtPatUpload = (TextView) findViewById(R.id.txt_pat_upload);
    	mImg0 = (ImageView) findViewById(R.id.auction_upload_imageView);
    	mImg1 = (ImageView) findViewById(R.id.auction_upload_imageView1);
    	mImg2 = (ImageView) findViewById(R.id.auction_upload_imageView2);
    	mImg3 = (ImageView) findViewById(R.id.auction_upload_imageView3);
    	mImg4 = (ImageView) findViewById(R.id.auction_upload_imageView4);
    	mImg5 = (ImageView) findViewById(R.id.auction_upload_imageView5);
    	mImg6 = (ImageView) findViewById(R.id.auction_upload_imageView6);
    	mImg7 = (ImageView) findViewById(R.id.auction_upload_imageView7);
    	
    	mEdtPriceMin = (EditText) findViewById(R.id.edt_price_min);
    	mEdtAddPrice = (EditText) findViewById(R.id.edt_add_price);
    	mTxtCategory = (TextView) findViewById(R.id.txt_category);
        mTxtCategory.setText(getResources().getStringArray(R.array.patCategory)[0]);
    	mEditName = (EditText) findViewById(R.id.edit_name);
    	mEdtContent = (EditText) findViewById(R.id.edt_content);
    	mStartTimeTextView = (TextView) findViewById(R.id.txt_pat_upload_starttime);
    	mEndTimeTextView = (TextView) findViewById(R.id.txt_pat_upload_endtime);
        mStartTimeTextView.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date())); //设置初始值
        mEndTimeTextView.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//设置初始值
        Intent intent = getIntent();
        if (intent.getStringExtra("flag") == null) {

        } else {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Auction auction = (Auction) bundle.getSerializable("auction");
                mEdtPriceMin.setText(auction.getPrice());
                mEdtAddPrice.setText(auction.getIncreaseNumber());
                mEditName.setText(auction.getTitle());
                mEdtContent.setText(auction.getIntroduce());
                mStartTimeTextView.setText(auction.getAdddate());
                mEndTimeTextView.setText(auction.getEditdate());
                mTxtCategory.setText(auction.getCategory());

            }
        }
    	
    }
    
    private void initListener() {
    	// 返回
    	mImgPatBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
    	// 选择商品类型
    	mTxtCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAlertDialogCategory();
			}
		});
    	// 设置开始时间
    	mStartTimeTextView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showCalendars(mStartTimeTextView);
			}
		});
    	// 设置结束时间
    	mEndTimeTextView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showCalendars(mEndTimeTextView);
			}
		});
		// 开始发送
		mTxtPatUpload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// 开始提交商品###
                mTxtPatUpload.setEnabled(false);
				cheakUpdate();
			}
		});
    }
    
    private void initImageListener() {
    	mImg0.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 0;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg1.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						mIndex = 1;
                        showDialogOrFullImage(mIndex);
					}
				});
		mImg2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 2;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg3.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 3;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg4.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 4;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg5.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 5;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg6.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 6;
                showDialogOrFullImage(mIndex);
			}
		});
		mImg7.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIndex = 7;
                showDialogOrFullImage(mIndex);
			}
		});
    }
    
    private void cheakUpdate() {
    	// 底价
    	mPriceMin = mEdtPriceMin.getText().toString();
        BigDecimal bigDecimal1 = null;
        try{
            bigDecimal1 = new BigDecimal(mPriceMin);
        }catch (NumberFormatException e){

        }

    	if(isEmpty(mPriceMin)) {
    		showToast("底价不能为空");
            mTxtPatUpload.setEnabled(true);
    		return;
    	}else if(bigDecimal1.compareTo(BigDecimal.valueOf(0))<=0){
            showToast("底价应大于0");
            mTxtPatUpload.setEnabled(true);
            return;
        }
    	
    	// 加价额
    	mAddPrice = mEdtAddPrice.getText().toString();
        BigDecimal bigDecimal = null;
        try{
            bigDecimal = new BigDecimal(mAddPrice);
        }catch (NumberFormatException e){

        }
    	if(isEmpty(mAddPrice)) {
    		showToast("加价额不能为空");
            mTxtPatUpload.setEnabled(true);
    		return;
    	}else if(bigDecimal.compareTo(BigDecimal.valueOf(0))<=0){
            showToast("加价额应大于0");
            mTxtPatUpload.setEnabled(true);
            return;
        }

        if (Double.parseDouble(mPriceMin) <= Double.parseDouble(mAddPrice)) {
            showToast("加价额不能高于底价");
            mTxtPatUpload.setEnabled(true);
            return;
        }
    	
    	// 开始时间
    	mStartTime = mStartTimeTextView.getText().toString();
    	// 结束时间
    	mEndTime = mEndTimeTextView.getText().toString();
    	if( mStartTime.compareTo(mEndTime) > 0 ) {
    		showToast("结束时间不能早于(或等于)开始时间");
            mTxtPatUpload.setEnabled(true);
    		return;
    	}
        Log.d(TAG, "mStartTime" + mStartTime); //2014-05-19
        Log.d(TAG, "mEndTime" + mEndTime);//2013-12-31
        //开始结束时间间隔不能大于30天
        if (DateTimeUtils.countTime(mStartTime, mEndTime) > (30 * 24 * 60)) {
            showToast("开始结束时间间隔不能大于30天");
            mTxtPatUpload.setEnabled(true);
            return;
        }

    	// 商品名字
    	mTitle = mEditName.getText().toString();
    	if(isEmpty(mTitle)) {
    		showToast("商品名称不能为空");
            mTxtPatUpload.setEnabled(true);
    		return;
    	}else if(mTitle.length()>30 || mTitle.length()<3){
            showToast("商品名称为3-30位");
            mTxtPatUpload.setEnabled(true);
            return;
        }
        if(!(mTitle.trim().length() >= 3 && mTitle.trim().length() <=30)) {
            showToast("商品名称必须是3-30位");
            mTxtPatUpload.setEnabled(true);
            return;
        }
    	
    	// 商品简介
    	mIntroduce = mEdtContent.getText().toString();
    	if(isEmpty(mIntroduce)) {
    		showToast("商品简介不能为空");
            mTxtPatUpload.setEnabled(true);
    		return;
    	}else if(mIntroduce.length()<=2){
            showToast("商品简介至少2位");
            mTxtPatUpload.setEnabled(true);
            return;
        }
        if(mIntroduce.trim().length() <= 2 ) {
            showToast("商品介绍字数应为2个以上");
            mTxtPatUpload.setEnabled(true);
            return;
        }
    	
    	if( mImagePaths[0] != null && !"".equals(mImagePaths[0]) && new File(mImagePaths[0]).exists() ) {
        	// 开始上传图片
        	uploadImages(0);
    	}else{
        	// ##可以上传了
        	startUpLoadData();
    	}
    	
    }
    
    private boolean isEmpty(String str) {
    	if( str != null && !"".equals(str.trim()) ) {
    		return false;
    	}
    	return true;
    }
    
    // 商品类型选择
    private void showAlertDialogCategory() {
    	final String[] categoryNames = getResources().getStringArray(R.array.patCategory);
    	new AlertDialog.Builder(this)
    	.setTitle("选择商品类型")
    	.setItems(categoryNames, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mSelectCategoryId = mCategoryIds[which];
				mTxtCategory.setText( categoryNames[which] );
			}
		}).show();
		
    }
    
    // 时间选择器
    private void showCalendars(final TextView textView) {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(UploadAuctionActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                textView.setText(year+"-"+( (monthOfYear+1)>9 ? (monthOfYear+1) : "0"+(monthOfYear+1) )+"-"+( dayOfMonth>9 ? dayOfMonth : "0"+dayOfMonth ));
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }
	
    // 上传图片
    private void showImageDialog() {
        new AlertDialog.Builder(this)
                .setTitle("上传图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                startActivityForResult(intentFromGallery, UploadImageUtils.IMAGE_REQUEST_CODE);
                                break;
                            case 1:
                                Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断存储卡是否可以用，可用进行存储
                                if (AppUtils.isExistSD()) {
                                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                                    File file = new File(path + "/" +IMAGE_FILE_NAME + mIndex + ".png");
                                    if( !file.exists() ) {
                                    	file.getParentFile().mkdirs();
                                    }
                                    intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                                }
                                startActivityForResult(intentFromCapture,UploadImageUtils.CAMERA_REQUEST_CODE);
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();

    }
    
    private String savePhoto(Bundle bundle) {
    	Bitmap bitmap;
        if (bundle != null) {
        	bitmap = bundle.getParcelable("data");
        }else{
        	return null;
        }
        
        FileOutputStream b = null;
        String pathPhoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/cache/";
        File file = new File(pathPhoto + IMAGE_FILE_NAME + mIndex + ".png");
		if(!file.exists()) {
	        file.getParentFile().mkdirs();// 创建文件夹
		}
        try {
            b = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
            	if( b!=null ) {
            		b.flush();
            		b.close();
            	}
                return file.getAbsolutePath();
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //结果码不等于取消时候
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case UploadImageUtils.IMAGE_REQUEST_CODE:
                    android.util.Log.e("switch", data.getData().toString());
                    String[] proj = { MediaStore.Images.Media.DATA };

                    Cursor actualimagecursor = managedQuery(data.getData(),proj,null,null,null);

                    int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                    actualimagecursor.moveToFirst();

                    String img_path = actualimagecursor.getString(actual_image_column_index);

                    File file = new File(img_path);
                    BitmapFactory.Options options1 =  new BitmapFactory.Options();
                    options1.inSampleSize = 4;
                    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),options1);
//                    UploadImageUtils.startPhotoZoom(MessagePublish.this, data.getData());
                    data.putExtra("data",bitmap);
                    android.util.Log.d("img_path", img_path);
                    data.putExtra("img_path",img_path);
                    savePath(data);
                    break;
                case UploadImageUtils.CAMERA_REQUEST_CODE:
                    if (AppUtils.isExistSD()) {
                        android.util.Log.e("SWITCH", data + "");
                        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                        File tempFile = new File(path + "/" +IMAGE_FILE_NAME + mIndex + ".png");
                        android.util.Log.e("switch", IMAGE_FILE_NAME + "－－－－" + mIndex);
//                        UploadImageUtils.startPhotoZoom(MessagePublish.this, Uri.fromFile(tempFile));
                        android.util.Log.e("Path", path.toString());
                        android.util.Log.e("tempFile", tempFile.getAbsolutePath() + "");
                        options1 =  new BitmapFactory.Options();
                        options1.inSampleSize = 4;
                        bitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath(),options1);
//                    UploadImageUtils.startPhotoZoom(MessagePublish.this, data.getData());
//                            data.putExtra("data",bitmap);
                        android.util.Log.d("img_path", tempFile.getAbsolutePath());
//                            data.putExtra("img_path",tempFile.getAbsolutePath());
                        picPath = tempFile.getAbsolutePath();
                        savePath(data);
                    } else {
                        Toast.makeText(UploadAuctionActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
                    }
                    break;
                case UploadImageUtils.RESULT_REQUEST_CODE: //图片缩放完成后

                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private Bitmap bitmap;
    String picPath;
    Drawable drawable = null;
    public void savePath(Intent data){
        if (data != null) {
            // 保存图片
            mImagePaths[mIndex] = savePhoto(data.getExtras());
            if( mImagePaths[mIndex] == null ) {
                Toast.makeText(this, "图片转换出错", Toast.LENGTH_SHORT).show();
                return;
            }
            android.util.Log.e("switch", mIndex + "-----" + data.getExtras());
            android.util.Log.e("switch", mImagePaths[mIndex] + "-----");
            Drawable drawable = UploadImageUtils.getImageToView(data, UploadAuctionActivity.this);
            switch (mIndex) {
                case 0:
                    mImg0.setImageDrawable(drawable);
                    mImg1.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    mImg1.setImageDrawable(drawable);
                    mImg2.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mImg2.setImageDrawable(drawable);
                    mImg3.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    mImg3.setImageDrawable(drawable);
                    mImg4.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    mImg4.setImageDrawable(drawable);
                    mImg5.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    mImg5.setImageDrawable(drawable);
                    mImg6.setVisibility(View.VISIBLE);
                    break;
                case 6:
                    mImg6.setImageDrawable(drawable);
                    mImg7.setVisibility(View.VISIBLE);
                    break;
                case 7:
                    mImg7.setImageDrawable(drawable);
                    break;
                default:
                    break;
            }
        }else {
            // 保存图片
            mImagePaths[mIndex] = picPath;
            if( mImagePaths[mIndex] == null ) {
                Toast.makeText(this, "图片转换出错", Toast.LENGTH_SHORT).show();
                return;
            }
            android.util.Log.e("switch", mIndex + "-----");
            android.util.Log.e("switch", mImagePaths[mIndex] + "-----");
//            Drawable drawable = UploadImageUtils.getImageToView(data, MessagePublish.this);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap photo = BitmapFactory.decodeFile(picPath, options);

            drawable = new BitmapDrawable(this.getResources(),photo);
            switch (mIndex) {
                case 0:
                    mImg0.setImageDrawable(drawable);
                    mImg1.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    mImg1.setImageDrawable(drawable);
                    mImg2.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mImg2.setImageDrawable(drawable);
                    mImg3.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    mImg3.setImageDrawable(drawable);
                    mImg4.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    mImg4.setImageDrawable(drawable);
                    mImg5.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    mImg5.setImageDrawable(drawable);
                    mImg6.setVisibility(View.VISIBLE);
                    break;
                case 6:
                    mImg6.setImageDrawable(drawable);
                    mImg7.setVisibility(View.VISIBLE);
                    break;
                case 7:
                    mImg7.setImageDrawable(drawable);
                    break;
                default:
                    break;
            }
        }
    }
    
    private void startUpLoadData() {

        if (!isLogin()) {
            startLoginOrRegistered();
            return;
        }

    	RequestParams params = new RequestParams();
    	params.put("mid", "17");
    	params.put("action", "add");
    	params.put("userid", DataCenter.userLogin.get(0).getUserid());
    	params.put("post[catid]", mSelectCategoryId+"");
    	params.put("post[price]", Float.parseFloat(mPriceMin) + "");
    	params.put("post[addlimit]", Float.parseFloat(mAddPrice) + "");
    	params.put("post[fromtime]", mStartTime);
    	params.put("post[totime]", mEndTime);
    	params.put("post[title]", mTitle);
    	params.put("post[introduce]", mIntroduce);
    	
    	for( int i=0; i<mImagePaths.length; i++ ) {
    		if( mImagePaths[i]!=null && !"".equals(mImagePaths[i].trim()) ) {
    			if( i==0 ) {
        			params.put("post[thumb]", mImagePaths[i]);
    			}else{
    				params.put("post[thumb"+i+"]", mImagePaths[i]);
    			}
    		}
    	}
        System.out.println("params--->"+params.toString());

        RequestClient.post(this, "http://www.3tixa.com:8086/kaiyi/member/my.php",params, new AsyncHttpResponseHandler(){

            @Override
            public void onStart() {
                if( !mLoadingDialog.isShowing() ) {
                    mLoadingDialog.show();
                }
            }

            @Override
            public void onSuccess(String content) {
                if (!HttpUtils.isConnected()){
                    showToast(R.string.no_network);
                    return;
                }else {
                    Toast.makeText(UploadAuctionActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    UploadAuctionActivity.this.finish();
                    System.out.println("content-->" + content);
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                Toast.makeText(UploadAuctionActivity.this, "上传失败，请重试！", Toast.LENGTH_SHORT).show();
                mTxtPatUpload.setEnabled(true);
                return;
            }

            @Override
            public void onFinish() {
                mTxtPatUpload.setEnabled(true);
                if( mLoadingDialog != null ) {
                    mLoadingDialog.dismiss();
                }
            }

        });
    }


    private void uploadImages(final int pos) {
    	
    	RequestParams params = new RequestParams();
    	params.put("moduleid", "17");
    	
    	try {
			params.put("upalbum", new File(mImagePaths[pos]));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
//    	params.put("oldurl", values); 	// 需要判断
    	
    	RequestClient.post(this, "http://www.3tixa.com:8086/kaiyi/appupload.php", params, new AsyncHttpResponseParse(this, new LoadDataHandler(){

			@Override
			public void onStart() {
				mLoadingDialog.show();
			}

			@Override
			public void onSuccess(String data) {
				if( data!=null ) {
					mImagePaths[pos] = data.substring(2, data.length()-2);
				}
				// 提交成功, 提交下一个
				if( pos <  mImagePaths.length - 1 ) {
					if( mImagePaths[pos+1]!=null && !"".equals(mImagePaths[pos+1]) ) {
						uploadImages(pos+1);
					}else{
						// 图片上传完毕
						/***开始上传信息**/
						startUpLoadData();
					}
				}else{
					// 图片上传完毕
					/***开始上传信息**/
					startUpLoadData();
				}
			}

			@Override
			public void onFailure(Throwable error, String content) {
				// 失败重新提交
				//uploadImages(pos);
                mLoadingDialog.dismiss();
                Toast.makeText(UploadAuctionActivity.this, "上传失败，请重试！", Toast.LENGTH_SHORT).show();
                mTxtPatUpload.setEnabled(true);
                return;
			}

    	}));
    }


    /**
     * 显示图片选择对话框，或者全屏浏览图片
     * @param mIndex
     */
    private void showDialogOrFullImage(int mIndex) {
        if (mImagePaths == null || mImagePaths[mIndex] == null || TextUtils.isEmpty(mImagePaths[mIndex].trim())) {
            showImageDialog();
        } else {
            startFullImage(mIndex);
        }
    }

    /**
     * 开启全屏图片浏览
     * @param defaultIndex
     */
    private void startFullImage(int defaultIndex) {
        Intent intent = new Intent(UploadAuctionActivity.this, ImageGalleryActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("defaultIndex", defaultIndex);
        ArrayList<String> imgPaths = new ArrayList<String>();
        for (String path : mImagePaths) {
            if (!TextUtils.isEmpty(path)) {
                imgPaths.add(path);
            }
        }
        bundle.putStringArrayList("imgPaths", imgPaths);
        intent.putExtras(bundle);
        startActivity(intent);
    }
    
}
